package com.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.beans.Person;
import com.bussiness.PersonBussinessProxy;
import com.constants.Constants;
import com.constants.ServiceEndPoints;
import com.constants.UIMessages;
import com.exceptions.DuplicateUserIdException;
import com.exceptions.ServiceUnavailableException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.validations.Validations;

/**
 * Servlet implementation class EditAccountServlet
 */
public class EditAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	PersonBussinessProxy personBI = new PersonBussinessProxy();

    /**
     * Default constructor. 
     */
    public EditAccountServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try
		{
			RequestDispatcher dispatcher;
			Person personData = new Person();
			HttpSession session = request.getSession(true);
			session.setMaxInactiveInterval(Constants.sessionTimeOut);
			personData = getInputData(request);
			if(validateForm(request,personData))
			{				
				//store ZIP code and address
				try
				{
					personData.setZipCode(Integer.parseInt(request.getParameter("zip").toString()));
				}
				catch(Exception e)
				{
					request.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
				}
				
				personData.setCustomerType(request.getParameter("categoryType"));
				
				String address1 = request.getParameter("address1").toString();
				String address2 = request.getParameter("address2").toString();
				personData.setAddress(address1 + "2:" + address2);
				
				personBI.setEndpoint(ServiceEndPoints.PersonEndPoint);
				
				try
				{
					//Encrypt password before sending the data to network
					byte[] encryptedpassword = personBI.encryptPassword(personData.getPassword());
					personData.setPassword(Base64.encode(encryptedpassword));
					
					personData= personBI.updateUser(personData);
					
					//Store User data to the session
					session.setAttribute("Name", personData.getFirstName() + "," + personData.getLastName());
					session.setAttribute("LastLoggedIn", personData.getLastLoggedIn());
					session.setAttribute("CustomerType", personData.getCustomerType());					
					session.setAttribute("PersonData", personData);
				}
				catch(DuplicateUserIdException ex)
				{
					request.setAttribute("ServerException", UIMessages.DUPLICATE_EMAIL);
					session.setAttribute("ServerException", UIMessages.DUPLICATE_EMAIL);
					dispatcher = getServletContext().getRequestDispatcher("/editUserAccount.jsp");
					dispatcher.forward(request, response);
					return;
				}
				catch(ServiceUnavailableException ex)
				{
					request.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
					session.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
					dispatcher = getServletContext().getRequestDispatcher("/editUserAccount.jsp");
					dispatcher.forward(request, response);
					return;
				}
				session.removeAttribute("ServerException");
				dispatcher = getServletContext().getRequestDispatcher("/subPages.jsp");
				dispatcher.forward(request, response);
			}
			else
			{
				dispatcher = getServletContext().getRequestDispatcher("/editUserAccount.jsp");
				dispatcher.forward(request, response);				
			}			
		}
		catch(Exception e)
		{
			HttpSession session = request.getSession(true);
			request.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
			session.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/editUserAccount.jsp");
			dispatcher.forward(request, response);
		}
	}

	public Person getInputData(HttpServletRequest request)
	{
		Person userData = new Person();
		
		try
		{
			//Getting the input parameter
			userData.setFirstName(request.getParameter("firstName").toString());
			userData.setLastName(request.getParameter("lastName").toString());
			userData.setCity(request.getParameter("city").toString());
			userData.setState(request.getParameter("state").toString());
			userData.setEmailId(request.getParameter("email").toString());
			userData.setPassword(request.getParameter("password1").toString());
			userData.setCustomerType(request.getParameter("categoryType").toString());
			return userData;
		}
		catch(Exception e)
		{
			request.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
			return null;
		}
		
	}
	
	public boolean validateForm(HttpServletRequest request,Person userData)
	{
		boolean bool=true;
		try
		{
			String address1 ="";
			String address2 ="";
			String zip ="";
			String password2="";
			
			//Getting the input parameter
			address1 = request.getParameter("address1").toString();
			address2 = request.getParameter("address2").toString();
			zip = request.getParameter("zip").toString();
			password2 =request.getParameter("password2").toString();
			
			//Storing the input parameter
			request.setAttribute("firstName", userData.getFirstName());
			request.setAttribute("lastName", userData.getLastName());
			request.setAttribute("address1", address1);
			request.setAttribute("address2", address2);
			request.setAttribute("city", userData.getCity());
			request.setAttribute("state", userData.getState());
			request.setAttribute("zip", zip);
			request.setAttribute("email", userData.getEmailId());
			request.setAttribute("MembershipType", userData.getCustomerType());
					
			if (!Validations.validateName(userData.getFirstName().trim())) 
			{
				request.setAttribute("firstnameException", UIMessages.INVALID_FIRSTNAME);
				bool=false;
			}
			if (!Validations.validateName(userData.getLastName().trim())) 
			{
				request.setAttribute("lastnameException",UIMessages.INVALID_LASTNAME);
				bool=false;
			}
			if (address1.trim().equalsIgnoreCase("") && address2.trim().equalsIgnoreCase("")) 
			{
				request.setAttribute("addressException",UIMessages.INVALID_ADDRESS);
				bool=false;
			}
			
			if (!Validations.validateName(userData.getCity().trim())) 
			{
				request.setAttribute("cityException",UIMessages.INVALID_CITY);
				bool=false;
			}
			if (!Validations.validateName(userData.getState().trim())) 
			{
				request.setAttribute("stateException",UIMessages.INVALID_STATE);
				bool=false;
			}
			if (!Validations.validateZip(zip.trim())) 
			{
				request.setAttribute("zipException",UIMessages.INVALID_ZIP);
				bool=false;
			}
			if (!Validations.validatePassword(userData.getPassword())) 
			{
				request.setAttribute("passwordException",UIMessages.INVALID_PASSWORD);
				bool=false;
			}
			if (!userData.getPassword().trim().equals("") && (password2.trim().equals("") || 
			!userData.getPassword().equals(password2))) 
			{
				request.setAttribute("confirmpassException",UIMessages.INVALID_CONFIRM_PASSWORD);
				bool=false;
			}
			return bool;
		}
		catch(Exception e)
		{
			request.setAttribute("ServerException", UIMessages.SERVICE_UNAVAILABLE);
			return false;
		}
		
	}
}
